// pages/team/publish/publish.js
import { guid } from '../../../utils/util';
import api from '../../../api/index';
import store from '../../../store/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusList: [
      '队员招募',
      "寻找团队"
    ],
    activeIndex: 0,
    imgs: [],
    active: false,
    contestName: '',//比赛名称
    name: '',//团队名称
    introduction: '',//团队/个人情况介绍
    needDatail: '',//招募要求
    needNum: Number,//招募人数
    currNum: 0, //当前队伍的人数
    contestID: '',//对应比赛的id
    status: 'need',  //当前队伍的状态：del/need/full
    mates: [],
    avatarUrl: '',
    nickName: '',
    type: '',
    isContest: false,
    tap: false,
    maxn: 20

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      contestID: options.id, //当前赛事的id
      contestName: options.name
    }, () => {
      console.log(this.data.contestID)
      if (this.data.contestID.length != 0) {
        console.log(this.data.contestID)
        this.setData({
          isContest: true
        })
      }
    })
    var activeIndex = options.index
    if (activeIndex == '1') {
      this.setData({
        activeIndex: 1
      })
    }
    this.setData({ uploadFile: this.uploadFile.bind(this), type: '' })

  },

  uploadFile: async function (files) {
    var paths = files.tempFilePaths;
    var urls = []
    for (var i = 0; i < paths.length; i++) {
      var res = await wx.cloud.uploadFile({
        cloudPath: guid() + '.png',
        filePath: paths[i]
      })
      urls.push(res.fileID);
    }
    return Promise.resolve({ urls });
  },

  uploadSuccess: function (e) {
    var imgs = [...this.data.imgs];
    for (var i = 0; i < e.detail.urls.length; i++) {
      imgs.push({ url: e.detail.urls[i] })
    }
    this.setData({ imgs, active: true });
  },

  deleteFile: function (e) {
    var imgs = [...this.data.imgs];
    imgs.splice(e.detail.index, 1)
    this.setData({ imgs }, this.checkActive)
  },
  navbarChange: function (e) {
    this.setData({ activeIndex: e.detail.index })
  },
  // 判断是否写完了，激活按钮
  checkActive: function () {
    const { name, contestName, introduction, needDatail, needNum } = this.data
    if (this.data.activeIndex == 0)
      this.setData({ active: name.length > 0 && contestName.length > 0 && introduction.length > 0 && needDatail.length > 0 && needNum.length > 0 })
    else {
      this.setData({ active: contestName.length > 0 && introduction.length > 0 })
    }
  },
  teamNameChange: function (e) {
    this.setData({ name: e.detail.value }, this.checkActive)
  },
  contestNameChange: function (e) {
    this.setData({ contestName: e.detail.value }, this.checkActive)
  },
  introChange: function (e) {
    this.setData({ userIntroduction: e.detail.value }, this.checkActive)
  },
  teamNumChange: function (e) {
    var maxn = this.data.maxn
    var value = e.detail.value
    if (value > maxn) {
      wx.showToast({
        title: '最多招募20人',
      })
    }
    value = value > maxn ? maxn : value
    this.setData({ needNum: value }, this.checkActive)
  },
  teamInfoChange: function (e) {
    this.setData({ introduction: e.detail.value }, this.checkActive)

  },
  zmChange: function (e) {
    // console.log( e.detail.value)
    this.setData({ needDatail: e.detail.value }, this.checkActive)
  },
  checkTap: function () {
    var tap = this.data.tap
    if (tap) {
      return 0
    }
    this.setData({
      tap: true
    })
    setTimeout(() => {
      this.setData({
        tap: false
      })
    }, 3500);
    return 1
  },

  submit: async function () {
    // let flag = 0;
    // console.log(store.contestList)
    // store.contestList.forEach(item => {
    //   // 比赛/活动名称 是进行中赛事的一项，才可以提交招募或寻找
    //   if (this.data.contestName === item.name) {
    //     flag = 1;
    //   }
    // })
    // if (flag == 1) {
      if (!this.checkTap()) {
        return 0
      }
      wx.showLoading({
        title: '提交中',
      })
      const { name, contestName, introduction, needDatail, needNum, imgs, contestID, mates, status, currNum } = this.data
      var imgUrls = [];
      for (var i = 0; i < imgs.length; i++) {
        imgUrls.push(imgs[i].url);
      }
      if (this.data.activeIndex == 0) {
        var params = { imgs: imgUrls, name, contestName, contestID, introduction, needDatail, needNum, mates, status, currNum }
        api.team.publish(params).then(res => {
          if (res.result.code == 200) {
            let pages = getCurrentPages();
            let prevPages = pages[pages.length - 2];

            prevPages.teamList()

            wx.navigateBack({
              delta: 1,
            })
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '发布成功',
                })
              },
            })
          } else {

            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '发布失败',
                })
              },
            })
          }
        })
      }
      else {
        var params = { imgs: imgUrls, contestName, introduction, contestID, status }
        api.player.publish(params).then(res => {
          console.log(res)
          let pages = getCurrentPages();
          let prevPages = pages[pages.length - 2];

          if (res.result.code === 200) {
            prevPages.teamList()
            wx.navigateBack({
              delta: 1,
            })
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '审核中',
                })
              },
            })

          } else {

            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '发布失败',
                })
              },
            })
          }
        })
      }
      console.log(params)  //获取表单数据
    // } else {
    //   wx.showToast({
    //     title: '比赛名称不存在',
    //     icon: 'error'
    //   })
    // }

  }
})